﻿#ifndef CHARACTER_COMMON_INCLUDED
#define CHARACTER_COMMON_INCLUDED

#include "UnityCG.cginc"

fixed4 _MainColor;
sampler2D _MainTex;
sampler2D _LightMapTex;

fixed _LightArea;
fixed _SecondShadow;
fixed4 _FirstShadowMultColor;
fixed4 _SecondShadowMultColor;

half _Shininess;
fixed _SpecMulti;

fixed3 _LightSpecColor;

fixed _Opaqueness;

fixed4 _LightColor0;
half _BloomFactor;

// Lighting functions
half diffuse_factor(half3 N, half3 L)
{
	// multiply by 0.4975 instead of 0.5 for some precision reason
	return dot(N, L) * 0.4975f + 0.5f;
}

half specular_factor(half3 N, half3 H, half shininess)
{
	return pow(max(dot(N, H), 0), shininess);
}

half rim_factor(half3 N, half3 V, half shininess)
{
	return pow(1.0f - max(0, dot(N, V)), shininess);
}

half front_factor(half3 N, half3 V, half shininess)
{
	return pow(max(0, dot(N, V)), shininess);
}

fixed3 complex_toon_diffuse(fixed factor, fixed t1, fixed t2, fixed3 baseTexColor)
{
	fixed3 diffColor = fixed3(1.0f, 1.0f, 1.0f).rgb;

	fixed D = t1 * t2;
	fixed threshold = 0;


	if (D < 0.09f)
	{
		threshold = (factor + D) * 0.5f;
		// in dark shadow
		if (threshold < _SecondShadow)
		{
			diffColor = baseTexColor * _SecondShadowMultColor; 
		}
		// in light shadow
		else
		{
			diffColor = baseTexColor * _FirstShadowMultColor;
		}
	}
	else 
	{
		// mapping [0.1, 0.5) to [-0.1, 0.5)
		if (D >= 0.5f) D = D * 1.2f - 0.1f;
		else D = D * 1.25f - 0.125f;

		threshold = (factor + D) * 0.5f;

		// in light shadow
		if (threshold < _LightArea)
		{
			diffColor = baseTexColor * _FirstShadowMultColor;
		}
		// in light
		else
		{
			diffColor = baseTexColor;
		}
	}

	return diffColor;
}


#endif // CHARACTER_COMMON_INCLUDED